package com.hboxs.asl.controller.app.member;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Page;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.Category;
import com.hboxs.asl.entity.Essay;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.service.CategoryService;
import com.hboxs.asl.service.EssayService;
import com.hboxs.asl.service.MemberService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller(value = "appMEssayController")
@RequestMapping(value = "/app/m/essay")
public class EssayController extends BaseController {

    @Resource(name = "essayServiceImpl")
    private EssayService essayService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name= "categoryServiceImpl")
    private CategoryService categoryService;

    /**
     * 删除文章
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage delete(long id) {
        essayService.delete(id);
        return JsonMessage.success("已删除");
    }

    /**
     * 编辑文章
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage edit(Essay essay) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if(essay != null) {
                essay.setMember(member);
                essayService.update(essay, "category");
                return JsonMessage.success("编辑成功");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 发布文章
     * @param essay
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage add(Essay essay, Long categoryId) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if (categoryId == null) {
                return JsonMessage.error("请选择分类标签");
            }
            essay.setMember(member);
            Category category = categoryService.find(categoryId);
            essay.setCategory(category);
            essayService.save(essay);
            return JsonMessage.success("文章发布成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 根据分类id获取文章
     * @param categoryId
     * @return
     */
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage get(Long categoryId, Pageable pageable) {
        try {
            Member teacher = memberService.getCurrentByToken();
            if(teacher == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Category category = categoryService.find(categoryId);
            if(category == null) {
                return JsonMessage.error("找不到该分类");
            }
            Page<Essay> page = essayService.findPageByCategory(pageable, teacher, category);

            return JsonMessage.success(

                    "totalPage", page.getTotalPages(),

                    "pageNumber", page.getPageNumber(),

                    "pageSize", page.getPageSize(),

                    "total", page.getTotal(),

                    "content", JsonMessage.optimiseObj(
                            page.getContent(),
                            "title", "id", "imageURL", "createDateF", "content", "contentWithoutTag"
                    )

            );

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 文章详情
     * @param essayId
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage detail(Long essayId, HttpServletRequest request) {
        try {
            Member teacher = memberService.getCurrentByToken();
            if(teacher == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            String path = request.getRequestURL().toString();
            String regex = request.getServletPath();
            int index = path.lastIndexOf(regex);
            String contentPath = path.substring(0, index);
            String url =  contentPath + "/app/essay/essayWeb.htm?essayId="+essayId;
            return JsonMessage.success(url);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 文章详情(id)
     * @param essayId
     * @return
     */
    @RequestMapping(value = "essay_detail", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage essayDetail(Long essayId) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Essay essay = essayService.find(essayId);
            if(essay == null) {
                return JsonMessage.error("找不到改文章");
            }
            return JsonMessage.success(JsonMessage.optimiseObj(essay, "id", "title", "content", "imageURL", "category.name", "category.id"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 根据老师id获取文章列表
     * @param teacherId
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage list(Long teacherId, Pageable pageable) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Member teacher = memberService.find(teacherId);
            if(teacher == null) {
                return JsonMessage.error("找不到该老师");
            }
            Page<Essay> page = essayService.findPageByTeacher(pageable, teacher);
            return JsonMessage.success(

                    "totalPage", page.getTotalPages(),

                    "pageNumber", page.getPageNumber(),

                    "pageSize", page.getPageSize(),

                    "total", page.getTotal(),

                    "content", JsonMessage.optimiseObj(
                            page.getContent(),
                            "title", "id", "imageURL", "createDate"
                    )

            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}
